#!D:\Python27\python.exe
# -*- coding: utf-8 -*-
'''
    Implements show avatar request command.
    
    :copyright: (c) 2014 by Duxin.
'''

import cgi
import os

import command
import app
import sessions
from db.db_manager import UserDAO, User
from exception import ParameterError

class Avatar(object):
    '''
        Find avatar by username and output avatar binary stream with CGI protocol.
        This command is publicly accessible.
    '''
    
    def is_param_right(self):
        form = cgi.FieldStorage()  
    
        if form.has_key('username'):
            self.username = form['username'].value
            return True
        else:
            print 'Content-type: text/html\n\nerror_参数不合法'
            return False

    def execute(self):
        user = UserDAO.find_by_username(self.username)

        if user:
            try: # Windows needs stdio set for binary mode.  
                import msvcrt  
                msvcrt.setmode (0, os.O_BINARY) # stdin  = 0  
                msvcrt.setmode (1, os.O_BINARY) # stdout = 1  
            except ImportError as e:  
                print "Status: 500 \n\n"
                return
            
            if user.avatars[0] is None:
                print "Status:404 \n\n"
                return
        
            print "Content-type: image/jpeg\n"
            print user.avatars[0]
        else:
            print "Status: 403 \n\n"

ava = Avatar()
if ava.is_param_right():
    ava.execute()
